	package com.qna;

import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qna.pojo.Question;

import java.io.File;
import java.security.Principal;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;



@Controller
@RequestMapping("/save")
public class SaveController {

    @RequestMapping(value="/save",method = RequestMethod.POST)
	public @ResponseBody Question getCoffeeInXML(HttpServletRequest request, Principal principal) {
	      String loggedInUser = principal.getName(); //get logged in username

    	long epoch = System.currentTimeMillis();
    	epoch = epoch/1000;
    	Question coffee = new Question();
        coffee.setShortDesc(request.getParameter("shortDesc"));
  coffee.setRelatedProduct(request.getParameter("relatedProduct"));
        coffee.setRelatedToTopic(request.getParameter("relatedToTopic"));
        if(request.getParameter("timestamp") != null && !(request.getParameter("timestamp").equalsIgnoreCase("0"))){
        	int i = Integer.parseInt(request.getParameter("timestamp"));
        	coffee.setTimestamp(i);
        }
        else{
        coffee.setTimestamp((int)epoch);
        }
        coffee.setSubmittedBy(loggedInUser);
        coffee.setIsDropdown(Boolean.valueOf(request.getParameter("isDropdown")));
        coffee.setIsFalse(Boolean.valueOf(request.getParameter("isFalse")));
        coffee.setIsTrue(Boolean.valueOf(request.getParameter("isTrue")));
        coffee.setIsTrueFalse(Boolean.valueOf(request.getParameter("isTrueFalse")));
        coffee.setNumberOfOptions(Integer.parseInt(request.getParameter("numberOfOptions")));
        coffee.setOptionOne(request.getParameter("optionOne"));
        coffee.setOptionSecond(request.getParameter("optionSecond"));
        coffee.setOptionThird(request.getParameter("optionThird"));
        coffee.setOptionFourth(request.getParameter("optionFourth"));
        coffee.setOptionFifth(request.getParameter("optionFifth"));
        coffee.setOptionSixth(request.getParameter("optionSixth"));
        coffee.setAnswer(request.getParameter("answer"));
		  try {
			  String desktop = System.getProperty ("user.home") + "/Desktop/yo/";
			File file = new File(desktop + coffee.getTimestamp() +".xml");
			JAXBContext jaxbContext = JAXBContext.newInstance(Question.class);
			Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
	 
			jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
	 
			jaxbMarshaller.marshal(coffee, file);
			jaxbMarshaller.marshal(coffee, System.out);
	 
		      } catch (JAXBException e) {
			e.printStackTrace();
		      }		
		return coffee;		
	}
	
}